<!--
 * @Author: XuMeiyi
 * @Date: 2021-10-25 18:12:52
 * @LastEditors: XuMeiyi
 * @LastEditTime: 2021-10-25 18:20:32
 * @Description: 轮播管理
-->
<template>
  <div>
    <!-- 添加和预览开始 -->
    <el-form :inline="true" :model="form" class="demo-form-inline">
      <el-button type="primary" style="margin-right: 10px" @click="toAdd"
        >添加</el-button
      >
      <el-button type="success" @click="toShow">预览</el-button>
    </el-form>
    <!-- 添加和预览结束 -->

    <!-- 表格开始 -->
    <div>
      <el-table
        :data="tableData"
        style="width: 100%; margin-top: 20px"
        v-loading="loading"
      >
        <el-table-column type="index" :index="1" label="序号" width="80px">
        </el-table-column>
        <el-table-column prop="id" label="编号"> </el-table-column>
        <el-table-column prop="name" label="名称"> </el-table-column>
        <el-table-column prop="introduce" label="描述"> </el-table-column>
        <el-table-column prop="url" label="图片">
          <template slot-scope="scope">
            <div>
              <!-- 图片悬浮触发的效果 -->
              <el-popover placement="right" trigger="hover">
                <el-image
                  slot="reference"
                  style="width: 60px; height: 30px"
                  :src="scope.row.url"
                ></el-image>
                <el-image
                  style="width: 300px; height: 200px"
                  :src="scope.row.url"
                ></el-image>
              </el-popover>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="80px">
          <!-- 通过插槽来设置状态的不同 -->
          <template slot-scope="scope">
            <div>
              <el-tag type="success" v-if="scope.row.status === '正常'"
                >正常</el-tag
              >
              <el-tag type="danger" v-else>停用</el-tag>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-button
              @click="toEdit(scope.row)"
              type="success"
              size="small"
              plain
              >编辑</el-button
            >
            <el-button
              @click="toDelete(scope.row.id)"
              type="danger"
              size="small"
              plain
              >删除</el-button
            >
            <el-button
              type="success"
              size="small"
              plain
              v-if="scope.row.status === '停用'"
              @click="toChangeStatus(scope.row, '启用')"
              >启用</el-button
            >
            <el-button
              type="warning"
              size="small"
              plain
              v-else
              @click="toChangeStatus(scope.row, '停用')"
              >停用</el-button
            >
          </template>
        </el-table-column>
      </el-table>
    </div>
    <!-- 表格结束 -->

    <!-- 模态框开始 -->
    <el-dialog :title="title" :visible.sync="visible">
      <el-form :model="form" :rules="rules" ref="myForm">
        <el-form-item
          label="轮播图名称"
          :label-width="formLabelWidth"
          prop="name"
        >
          <el-input v-model="form.name" autocomplete="off" clearable></el-input>
        </el-form-item>
        <el-form-item label="轮播图描述" :label-width="formLabelWidth">
          <el-input
            v-model="form.introduce"
            autocomplete="off"
            clearable
          ></el-input>
        </el-form-item>
        <el-form-item
          label="轮播图图片"
          :label-width="formLabelWidth"
          prop="url"
        >
          <el-upload
            class="avatar-uploader"
            :action="uploadFileURL"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload"
          >
            <img
              v-if="imageUrl"
              :src="form.url"
              class="avatar"
              style="width: 300px"
            />
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>
        <el-form-item label="状态" :label-width="formLabelWidth" prop="status">
          <el-input type="text" v-model="form.status" clearable></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="visible = false">取 消</el-button>
        <el-button type="primary" @click="toSubmit('myForm')">确 定</el-button>
      </div>
    </el-dialog>
    <!-- 模态框结束 -->

    <!-- 预览的模态框开始 -->
    <el-dialog :title="title" :visible.sync="carouselVisible" width="600px">
      <!-- 轮播图 -->
      <div class="block">
        <el-carousel height="300px" width="100%">
          <el-carousel-item v-for="(item, index) in tableData" :key="index">
            <el-image :src="item.url"></el-image>
          </el-carousel-item>
        </el-carousel>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="carouselVisible = false">关 闭</el-button>
      </span>
    </el-dialog>
    <!-- 预览的模态框结束 -->
  </div>
</template>

<script>
import { findAll, deleteById, saveOrUpdate, query } from "@/api/carousel";
//图片上传的路径
import { showFileURL, uploadFileURL } from "@/utils/config";

export default {
  data() {
    return {
      loading: false,
      form: {},
      tableData: [],
      visible: false,
      formLabelWidth: "120px",
      title: "",
      imageUrl: "",
      showFileURL,
      uploadFileURL,
      //表单校验的事件
      rules: {
        name: [
          { required: true, message: "请输入轮播图的名称", trigger: "blur" },
        ],
        price: [{ required: true, message: "请输入产品价格", trigger: "blur" }],
        url: [
          { required: true, message: "请选择轮播图的图片", trigger: "blur" },
        ],
        status: [
          { required: true, message: "请输入轮播图的状态", trigger: "blur" },
        ],
      },
      carouselVisible: false,
    };
  },
  methods: {
    //查询所有轮播图
    async findAllCarousel() {
      this.loading = true;
      let res = await findAll();
      // console.log(res);
      this.tableData = res.data;
      this.loading = false;
    },
    //给新增按钮绑定事件
    toAdd() {
      this.visible = true;
      this.title = "新增轮播图信息";
      this.form = {};
      this.imageUrl = "";
    },
    //给编辑按钮绑定事件
    toEdit(row) {
      this.visible = true;
      this.title = "修改轮播图信息";
      this.form = { ...row };
      this.imageUrl = this.form.url;
    },
    //给删除按钮绑定事件
    toDelete(id) {
      this.$confirm("此操作将永久删除该轮播图, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }) //async要放在离await最近的函数名上
        .then(async () => {
          let res = await deleteById({ id });
          this.findAllCarousel();
          this.$message({
            type: "success",
            message: "删除成功!",
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    //给轮播图状态的改变绑定事件
    async toChangeStatus(row, text) {
      if (text === "启用") {
        row.status = "正常";
      } else {
        row.status = "停用";
      }
    },
    //给模态框确定按钮绑定事件
    toSubmit(formName) {
      this.$refs[formName].validate(async (valid) => {
        if (valid) {
          let res = await saveOrUpdate(this.form);
          this.visible = false;
          this.$message({
            type: "success",
            message: res.message,
          });
          //刷新页面
          this.findAllCarousel();
        } else {
          //校验失败执行的结果
          this.$message.error("保存失败");
          return false;
        }
      });
    },
    //图标添加框的事件
    //图标上传成功的事件
    handleAvatarSuccess(res, file) {
      this.imageUrl = URL.createObjectURL(file.raw);
      // console.log(res);
      this.form.url = showFileURL + res.data.id;
    },
    //图标上传之前的事件
    beforeAvatarUpload(file) {
      const isJPG = file.type === "image/jpeg";
      const isLt2M = file.size / 1024 / 1024 < 2;
      if (!isJPG) {
        this.$message.error("上传图标只能是 JPG 格式!");
      }
      if (!isLt2M) {
        this.$message.error("上传图标的大小不能超过 2MB!");
      }
      return isJPG && isLt2M;
    },
    //给预览按钮绑定事件
    toShow() {
      this.carouselVisible = true;
      this.title = "轮播图预览";
    },
  },
  created() {
    this.findAllCarousel();
  },
};
</script>

<style lang="less" scoped>
</style>
